package org.nowcoder.leetcode.twoPointers;

import java.util.HashSet;
import java.util.Set;

/**
 * Title  : 142. Linked List Cycle II
 * Source : https://leetcode.cn/problems/linked-list-cycle-ii/description/
 * Author : XrazYang
 * Date   : 2023-10-24
 */

public class LeetCode_142 {

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode detectCycle(ListNode head) {
        //直观了当解法，更快的方法：快慢指针
        Set<ListNode> set = new HashSet<>();
        ListNode p = head;
        while (p != null) {
            if (set.contains(p)) {
                return p;
            }
            set.add(p);
            p = p.next;
        }
        return null;
    }
}
